import { ActionReducerMapBuilder, AsyncThunk, createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import type { Doc, DocParams, KnowledgePage, KnowledgeParams } from '@/type/HomeTyoe';
import type { AsyncThunkConfig } from '@reduxjs/toolkit/dist/createAsyncThunk';
import type { Page } from '@/type/ResponseType';
import { fetchDocListAPI, fetchKnowledgeListAPI } from '@/API/homeAPI';

type ReducersAction = { type: string, payload: { id: string, like: 0 | 1 } };


type InitialState = {
  knowledgePage: KnowledgePage
  docList: Doc[]
}

const initialState = {
  knowledgePage: {} as KnowledgePage,
  docList: [],
};

/**
 * @description 获取首页问诊列表的异步函数
 * */
export const fetchKnowledgeList: AsyncThunk<KnowledgePage, KnowledgeParams, AsyncThunkConfig> = createAsyncThunk('fetchKnowledgeList', async (knowledgeParams, { rejectWithValue }) => {
  try {
    const { data } = await fetchKnowledgeListAPI(knowledgeParams);
    return data;
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});

/**
 * @description 获取关注医生列表的异步函数
 * */
export const fetchDocList: AsyncThunk<Page<Doc[]>, DocParams, AsyncThunkConfig> = createAsyncThunk('fetchDocList', async (docParams, { rejectWithValue }) => {
  try {
    const { data } = await fetchDocListAPI(docParams);
    return data;
  } catch (error: any) {
    return rejectWithValue(error.message);
  }

});
const homeStore = createSlice({
  name: 'homeStore',
  initialState,
  reducers: {
    followLikeDoctor(state: InitialState, action: ReducersAction) {
      const { id, like } = action.payload;
      const doctor = state.docList.find(item => item.id === id) as Doc;
      doctor.likeFlag = like;
    },
  },
  extraReducers(builder: ActionReducerMapBuilder<InitialState>) {
    builder.addCase(fetchDocList.fulfilled, (state: InitialState, action: PayloadAction<Page<Doc[]>>) => {
      const { payload } = action;
      state.docList = payload.rows;
    });
  },
});

export const { followLikeDoctor } = homeStore.actions;

export default homeStore.reducer;